package com.changgou.controller;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.Result;
import com.changgou.feign.OrderFeign;
import com.changgou.feign.WxPayFeign;
import com.changgou.pojo.Order;
import com.changgou.web.CasUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.Map;

@Controller
public class PayController {

    @Autowired
    private OrderFeign orderFeign;

    @Autowired
    private WxPayFeign wxPayFeign;

    /**
     * 微信支付
     * @param orderId
     * @return
     */
    @GetMapping("/wxPay")
    public String wxPay(String orderId, Model model){

        //1.调用订单api, 查询订单，并校验

        Result orderResult = orderFeign.findById( orderId );
        if(orderResult.getData()==null){
            return "fail";
        }
        Order order = JSON.parseObject( JSON.toJSONString( orderResult.getData() ), Order.class );
        //状态
        if(!"0".equals( order.getPayStatus() )){
            return "fail";
        }
        //用户名校验
        if( !order.getUsername().equals( CasUtil.loginName() ) ){
            return "fail";
        }

        //2.调用支付api的微信统一下单接口

        Result payResult = wxPayFeign.nativePay( orderId, order.getPayMoney() );
        Map<String,String> payMap = (Map<String,String>)payResult.getData();
        if(payMap==null){
            return "fail";
        }

        if(!"SUCCESS".equals(payMap.get( "result_code" )    )){
            return "fail";
        }

        model.addAttribute( "orderId" ,orderId);
        model.addAttribute( "money",order.getPayMoney() );
        model.addAttribute( "code_url" ,payMap.get( "code_url" ) );

        return "wxpay";
    }

}
